package com.emotionalEnvelope.edu.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.emotionalEnvelope.edu.model.User;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description
 * @Author lqq
 * @Date 2023/03/12 21:42
 */
@Component
public class MyTokenUtil {
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;
    /**
     * 密钥盐
     */
    private static final String TOKEN_SECRET = "lqq.com";

    private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 签名生成
     *
     * @param user
     * @return
     */
    public static String sign(User user) {
        String token = null;
        try {
            Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            token = JWT.create()
                    .withIssuer(user.getAccount())
                    .withClaim("id", user.getId().toString())
                    .withExpiresAt(expiresAt)
                    // 使用了HMAC256加密算法。
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 签名验证
     *
     * @param token
     * @return
     */
    public static String verify(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
            DecodedJWT jwt = verifier.verify(token);
            System.out.println("认证通过：");
            System.out.println("id: " + jwt.getClaim("id").asString());
            System.out.println("过期时间：      " + format.format(jwt.getExpiresAt()));
            return jwt.getClaim("id").asString();
        } catch (Exception e) {
            return null;
        }
    }

    public static String toID(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim("id").asString();
        } catch (Exception e) {
            return null;
        }
    }

}
